package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.R;
import com.itheima.entity.User;
import com.itheima.service.UserService;
import com.itheima.utils.SMSSendCode;
import com.itheima.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String phone = user.getPhone();
        log.info("发送验证码的手机号为:{}",phone);
        //生成一个验证码
        if(phone!=null&&phone.length()!=0){
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            log.info("phone:{},code:{}",phone,code);
            // 服务器存一个
//            session.setAttribute(phone,code);//这个手机号对应的验证码
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            // 验证码发给客户
            try {
//                SMSSendCode.sendCode(phone,code);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return R.success(code);
        }
        return R.error("手机号不存在,请更正后重试");
    }

    /**
     * 用户登录
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody User user,HttpSession session){
        log.info("用户的登录信息:{}",user);
        String userPhone = user.getPhone();
        String userCode = user.getCode();
//        String sessionCode = (String) session.getAttribute(userPhone);

        Object sessionCode = redisTemplate.opsForValue().get(userPhone);

        if(!userCode.equals(sessionCode)){
            log.info("用户输入的验证码不正确");
            return R.error("您输入的验证码不正确");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,userPhone);
        User one = userService.getOne(wrapper);
        if(one == null){ //数据库中没有这个手机号
            log.info("该手机号尚未注册,立即注册");
            user.setStatus(1);
            user.setName("吃货_"+userPhone);
            userService.save(user);
            one = user;
        }
        //登录  session 中存入数据
        session.setAttribute("userId",one.getId());
        //清理redis code缓存
        redisTemplate.delete(userPhone);
        return R.success(one);
    }

    /**
     * 用户登出
     * @return
     */
    @PostMapping("/loginout")
    public R loginout(){
        return R.success("成功");
    }

}
